'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = {
  ...require(__dirname + '/config.js')[env],
  define: {
    underscored: true,
  },
};
// const config = require(__dirname + '/..\config\config.js')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}
// 测试是否连接成功
// sequelize 
//   .authenticate()
//   .then(() => {
//     console.log('Connection has been established successfully.');
//   })
//   .catch(err => {
//     console.error('Unable to connect to the database:', err);
//   });
fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf(".") !== 0) && (file !== "index.js") && (file !== "config.js");//这边看教程 是木有config.js的排除。这又是由于sequelize-cli 初始化的时候，配置文件不管用。。。所以自己更改了init创建的文件夹的路径。造成后去各种问题。这里的问题，在sequelize.js中的392行开始，可以看到 defineCall是function，调试之后可以发现，由于改目录的问题，造成了config.js出现在models中。
  })
  .forEach(file => {
    const model = sequelize.import(path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

//http://docs.sequelizejs.com/manual/tutorial/models-usage.html#data-retrieval-finders ;sequelize api link